package org.gnomus.server.controllers;

import org.gnomus.data.access;
import org.gnomus.data.assignment;
import org.gnomus.data.store;
import org.gnomus.server.Context;
import org.gnomus.server.Controller;

import javax.servlet.ServletOutputStream;
import java.io.IOException;

public class Lab implements Controller {
    public String code;
    public String code_0;
    public String code_1;
    public String code_2;
    public String code_3;
    public String score;

    public boolean landing() {
        Context ctx = Context.get();
        if("post".equals(ctx.method.toLowerCase())) {
            assert code != null || (code_0 != null && code_1 != null && code_2 != null && code_3 != null);
            if (code == null) {
                code = code_0 + " " + code_1 + " " + code_2 + " " + code_3;
            }
            access acs = access.findByCode(code.trim());
            if (acs != null) {
                assignment ant = acs.getAssignment();
                ctx.redirect("/lab/" + ant.getLab() + "?code=" + code);
            } else {
                ctx.errors.put("code", "Invalid code '" + code + "'");
            }
        }
        return true;
    }

    public boolean atomicNuclei() {
        if (code != null) {
            access acs = access.findByCode(code);
            if (acs != null && Boolean.FALSE.equals(acs.getUsed())) {
                acs.setUsed(true);
                acs.save();
            }
        }
        return true;
    }

    public boolean periodicSquares() {
        if (code != null) {
            access acs = access.findByCode(code);
            if (acs != null && Boolean.FALSE.equals(acs.getUsed())) {
                acs.setUsed(true);
                acs.save();
            }
        }
        return true;
    }

    public boolean periodicSquaresPreTest() {
        return true;
    }

    public boolean recordScore() {
        assert code != null;
        assert score != null;
        access acs = access.findByCode(code);
        if (acs != null) {
            acs.recordScore(score);
        }
        try {
            ServletOutputStream out = Context.get().res.getOutputStream();
            out.write((acs != null ? "You have complete this lab and your score has been recorded." :
                    "Whoops. Something went wrong when recording your score.").getBytes());
            out.flush();
        } catch (IOException e) {
            throw new Error(e);
        }
        return true;
    }
}
